<?php
/**
 * 解析fba收支汇总报表-数据入库
 * User: bgl
 * Date: 2023/11/10
 * Time: 18:08
 */

namespace App\Logic\Amazon\Api\Parse;


use App\Models\Amazon\AmazonSkuName;
use App\Models\Amazon\LedgerDetailView;
use App\Models\Amazon\LedgerSummaryView;

class GetLedgerSummaryViewData{

    public static function exe($lines,$accountId){

        if(!$accountId)return 2;
        if(!is_array($lines))return 2;
        $i = 0;
        $count = 0;
        try{
            foreach($lines as $line){
                $flag = self::_addFbaFulfillment($line,$accountId);
                $flag && $count++;
                $i++;
            }
        }catch (\Exception $e){
            report($e);
        }
        return $i == $count ? 1 : 2;
    }

    /**
     * @param $line
     * @param $accountId
     * @return bool
     */
    private static function _addFbaFulfillment($line,$accountId){

        //AmazonSkuName::addName($line['MSKU'],$line['Title']);

        $receivedDate = gmdate('Y-m-d H:i:s',strtotime($line['Date']));
        $item = [
            'date' => $receivedDate,
            'account_id' => $accountId,
            'fnsku' => $line['FNSKU'],
            'seller_sku' => $line['MSKU'],
            'title' => $line['Title'],
            'disposition' => $line['Disposition'], //处置方式
            'starting_warehouse_balance' => $line['Starting Warehouse Balance'], //仓库开始余数
            'in_transit_between_warehouses' => $line['In Transit Between Warehouses'], //仓库调拨数量
            'receipts' => $line['Receipts'], //接收到货数量
            'customer_shipments' => $line['Customer Shipments'], //客户发运数量
            'customer_returns' => $line['Customer Returns'], //客户退货数量
            'vendor_returns' => $line['Vendor Returns'], //供应商退货数量
            'warehouse_transfer_in_out' => $line['Warehouse Transfer In/Out'], //仓库进/出转移数量
            'found' => $line['Found'], //找回数量
            'lost' => $line['Lost'], //遗失数量
            'damaged' => $line['Damaged'], //破损数量
            'disposed' => $line['Disposed'], //处理数量
            'ending_warehouse_balance' => $line['Ending Warehouse Balance'], //仓库最后余数
            'other_events' => $line['Other Events'], //其他事件
            'unknown_events' => $line['Unknown Events'], //未知事件
            'location' => $line['Location'], //发运标识
        ];

        //$count = LedgerDetailView::query()
        //    ->where('received_date',$receivedDate)
        //    ->where('seller_sku',$line['MSKU'])
        //    ->where('quantity',$line['Quantity'])
        //    ->where('fba_shipment_id',$line['fba-shipment-id'])
        //    ->where('fulfillment_center_id',$line['FulfillmentCenter'])
        //    ->count();
        //if($count > 0)return true;

        $re = LedgerSummaryView::query()->create($item);
        return !$re ? false : true;
    }

}
